# app/__init__.py
from datetime import timedelta

from flask import Flask, jsonify
from flask_migrate import Migrate
from flask_session import Session
from app.db import db
from app.routes.main_routes import main_bp
from app.routes.auth_routes import auth_bp
from app.routes.prediction_routes import prediction_bp
import logging
from app.model_loader import preload_models, preloaded_models as loaded_models  # 修改导入语句

app = Flask(__name__)
app.config.from_object('config.Config')
app.config['SECRET_KEY'] = 'your_secret_key'
app.config['SESSION_TYPE'] = 'filesystem'
app.config['PERMANENT_SESSION_LIFETIME'] = timedelta(minutes=30)  # 设置会话有效期为 30 分钟
# 配置数据库连接池
app.config['SQLALCHEMY_POOL_SIZE'] = 20  # 连接池大小
app.config['SQLALCHEMY_MAX_OVERFLOW'] = 30  # 最大溢出连接数

Session(app)
db.init_app(app)
migrate = Migrate(app, db)  # 初始化 Flask-Migrate

app.register_blueprint(main_bp)
app.register_blueprint(auth_bp)
app.register_blueprint(prediction_bp)

# 定义一个标志变量
first_request = True

# 全局错误处理
@app.errorhandler(Exception)
def handle_exception(e):
    logging.error(f"An error occurred: {str(e)}", exc_info=True)
    return jsonify({"error": "An internal server error occurred."}), 500

# 在应用初始化时预加载模型
with app.app_context():
    db.create_all()
    try:
        logging.info("Starting to preload models...")
        preload_models()
        logging.info("Models preloaded successfully.")
    except Exception as e:
        logging.error(f"Failed to preload models: {str(e)}", exc_info=True)
